<template>
  <el-card>
    <el-form inline>
      <el-form-item>
        <el-input placeholder="用户名" v-model="username" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="search">
          搜索
        </el-button>
        <el-button @click="reset"> 清空 </el-button>
      </el-form-item>
    </el-form>

    <el-button type="primary" @click="showSaveUser"> 添加用户 </el-button>
    <el-button type="danger"> 批量删除 </el-button>

    <el-table
      :data="userList"
      v-loading="loading"
      border
      class="mt-20"
      row-key="id"
    >
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column prop="username" label="用户名" width="100" />
      <el-table-column prop="nickName" label="用户昵称" width="200" />
      <el-table-column prop="roleName" label="角色列表" width="200" />
      <el-table-column prop="gmtCreate" label="创建时间" width="200" />
      <el-table-column prop="gmtModified" label="更新时间" width="300" />
      <el-table-column label="操作" fixed="right" width="300">
        <template v-slot="{ row }">
          <el-button
            type="info"
            :icon="User"
            size="small"
            @click="showRoleDialog(row)"
          />
          <el-button type="warning" :icon="Edit" size="small" />
          <el-button type="danger" :icon="Delete" size="small" />
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="mt-20"
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      @size-change="getUserList"
      @current-change="getUserList"
    />

    <el-dialog v-model="dialogVisible" title="添加用户">
      <el-form
        label-width="100px"
        ref="userFormRef"
        :model="userFormData"
        :rules="userFormRules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userFormData.username" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="userFormData.nickName" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userFormData.password" type="password" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="roleDialogVisible" title="分配用户角色">
      <el-form
        label-width="100px"
        ref="roleFormRef"
        :model="roleFormData"
        :rules="roleFormRules"
      >
        <el-form-item label="用户名">
          <el-input v-model="roleFormData.username" disabled />
        </el-form-item>
        <el-form-item label="角色列表" prop="roleId">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group
            v-model="roleFormData.roleId"
            @change="handleCheckedRoleChange"
          >
            <el-checkbox
              v-for="role in allRolesList"
              :key="role.id"
              :label="role.id"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="assignUserRoleList">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "XUser",
};
</script>

<script lang="ts" setup>
import { Delete, Edit, User, Search } from "@element-plus/icons-vue";
import { ref, onMounted, reactive } from "vue";
import {
  getUserListApi,
  saveUserApi,
  getUserRoleListApi,
  assignUserRoleListApi,
} from "@/api/acl/user";
import type { UserList, UserItem, RoleList } from "@/api/acl/model/userModel";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(3);
const total = ref(0);

const userList = ref<UserList>([]);
const username = ref("");
const isSearch = ref(false);

const getUserList = async () => {
  loading.value = true;
  const res = await getUserListApi(
    currentPage.value,
    pageSize.value,
    isSearch.value ? username.value : ""
  );
  userList.value = res.items;
  total.value = res.total;
  loading.value = false;
};
// 搜索
const search = () => {
  isSearch.value = true;
  getUserList();
};
// 清空
const reset = () => {
  username.value = "";
  currentPage.value = 1;
  pageSize.value = 3;
  isSearch.value = false;
  getUserList();
};

onMounted(getUserList);

const dialogVisible = ref(false);

const showSaveUser = () => {
  dialogVisible.value = true;
  userFormData.username = "";
  userFormData.nickName = "";
  userFormData.password = "";
  userFormRef.value?.clearValidate();
};

const userFormRef = ref<FormInstance>();
const userFormData = reactive({
  username: "",
  nickName: "",
  password: "",
});
const userFormRules = reactive<FormRules>({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  nickName: [{ required: true, message: "请输入用户昵称", trigger: "blur" }],
  password: [{ required: true, message: "请输入用户密码", trigger: "blur" }],
});

// 添加用户
const saveUser = async () => {
  await userFormRef.value?.validate();
  await saveUserApi(userFormData);
  ElMessage.success("添加用户成功");
  dialogVisible.value = false;
  getUserList();
};

const roleDialogVisible = ref(false);
const allRolesList = ref<RoleList>([]);

const showRoleDialog = async (row: UserItem) => {
  roleFormData.userId = row.id;
  roleFormData.username = row.username;
  const res = await getUserRoleListApi(row.id);
  // 请求回来数据有两项值：assignRoles（用户目前拥有的角色） allRolesList（所有角色列表）
  roleFormData.roleId = res.assignRoles.map((role) => role.id);
  allRolesList.value = res.allRolesList;
  // 全选-全不选-半选
  handleCheckedRoleChange(roleFormData.roleId);

  roleDialogVisible.value = true;
  roleFormRef.value?.clearValidate();
};

const roleFormRef = ref<FormInstance>();
const roleFormData = reactive<{
  userId: string;
  username: string;
  roleId: string[];
}>({
  userId: "",
  username: "",
  roleId: [],
});
const roleFormRules = reactive<FormRules>({
  roleId: [{ required: true, message: "请选择角色", trigger: "blur" }],
});

// 全选-全不选-半选
const checkAll = ref(false);
const isIndeterminate = ref(false);
const handleCheckAllChange = (val: string | number | boolean) => {
  // 更新全选-全不选
  if (val) {
    // 全选
    roleFormData.roleId = allRolesList.value.map((role) => role.id);
    return;
  }
  // 全不选
  roleFormData.roleId = [];
};

const handleCheckedRoleChange = (value: any) => {
  // // 半选
  // if (value.length >= 1 && value.length < allRolesList.value.length) {
  //   isIndeterminate.value = true;
  //   return;
  // }

  // isIndeterminate.value = false;

  // // 全选和全不选
  // if (value.length === 0) {
  //   checkAll.value = false;
  // } else if (value.length === allRolesList.value.length) {
  //   checkAll.value = true;
  // }

  // 半选
  isIndeterminate.value = false;

  // 全选和全不选
  if (value.length === 0) {
    checkAll.value = false;
  } else if (value.length === allRolesList.value.length) {
    checkAll.value = true;
  } else {
    isIndeterminate.value = true;
  }
};

const assignUserRoleList = async () => {
  await roleFormRef.value?.validate();
  await assignUserRoleListApi(roleFormData.userId, roleFormData.roleId);
  ElMessage.success("分配用户角色成功");
  roleDialogVisible.value = false;
  getUserList();
};
</script>

<style scoped></style>
